package com.chenfan.magic.config;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

/**
 * 动态表明配置Helper
 * @author wulg
 * @date 2024/6/3
 */
@RefreshScope
@Slf4j
@Configuration
public class DynamicTableHelper implements InitializingBean {

    @Autowired
    private NacosConfigManager nacosConfigManager;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @Value("${magic.dynamicTable.dataId:magic-dynamic-table.json}")
    private String dataId;

    private static Map<String, Map<String, String>> tableMap = new ConcurrentHashMap<>(128);

    @Override
    public void afterPropertiesSet() throws Exception {
        String configInfo = nacosConfigManager.getConfigService().getConfig(dataId, nacosConfigProperties.getGroup(), 5000);
        //初始化
        log.info("常规版/纯净版取动态表名配置初始化：{}", configInfo);
        DynamicTableHelper.updateDynamicTableMap(configInfo);
        //nacos配置变更监听
        nacosConfigManager.getConfigService().addListener(dataId, nacosConfigProperties.getGroup(), new Listener() {

                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    try {
                        log.info("常规版/纯净版取动态表名配置更新：{}", configInfo);
                        DynamicTableHelper.updateDynamicTableMap(configInfo);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        //TODO 告警
                    }
                }
         });
    }

    public static synchronized  void updateDynamicTableMap(String configInfo) {
        tableMap.clear();
        List<DynamicTableConfig> configList = JSONObject.parseObject(configInfo, new TypeReference<List<DynamicTableConfig>>(){});
        if(CollectionUtils.isEmpty(configList)) {
            return;
        }
        for(DynamicTableConfig config : configList) {
            if(!ObjectUtils.defaultIfNull(config.getEnabled(), Boolean.FALSE).booleanValue()) {
                continue;
            }
            if(MapUtils.isEmpty(config.getDynamicTableMap())) {
                tableMap.put(config.getIndexName(), new HashMap<>(0));
            } else {
                tableMap.put(config.getIndexName(), config.getDynamicTableMap());
            }

        }
    }

    /**
     * 根据指标名获取动态表名
     * @param indexName
     * @return
     */
    public static Map<String, String> getDynamicTableMapByIndex(String indexName) {
        return tableMap.get(indexName);
    }

    /**
     * 动态表配置
     */
    @Data
    public static class DynamicTableConfig {
        /**
         * 指标名
         */
        private String indexName;
        /**
         * 开关
         */
        private Boolean enabled;

        /**
         * 动态表MAP：key:常规版表 value:纯净版表
         */
        private Map<String, String> dynamicTableMap;
    }
}
